﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.IO;
using System.Text;

namespace DataService.Core.Common
{
    public static class FileHelper
    {
        /// <summary>打开并写入</summary>
        /// <param name="file">文件信息</param>
        /// <param name="compressed">是否压缩</param>
        /// <param name="func">要对文件流操作的委托</param>
        /// <returns></returns>
        public static Int64 OpenWrite(this FileInfo file, Boolean compressed, Action<Stream> func)
        {
            file.FullName.EnsureDirectory(true);

            using (var fs = file.OpenWrite())
            {
                if (compressed)
                {
                    using (var gs = new GZipStream(fs, CompressionLevel.Optimal, true))
                    {
                        func(gs);
                    }
                }
                else
                {
                    func(fs);
                }

                fs.SetLength(fs.Position);

                return fs.Position;

            }

        }


        /// <summary>打开并读取</summary>
        /// <param name="file">文件信息</param>
        /// <param name="compressed">是否压缩</param>
        /// <param name="func">要对文件流操作的委托</param>
        /// <returns></returns>
        public static Int64 OpenRead(this FileInfo file, Boolean compressed, Action<Stream> func)
        {
            if (compressed)
            {
                using var fs = file.OpenRead();
                using var gs = new GZipStream(fs, CompressionMode.Decompress, true);
                using var bs = new BufferedStream(gs);
                func(bs);
                return fs.Position;
            }
            else
            {
                using var fs = file.OpenRead();
                func(fs);
                return fs.Position;
            }
        }

        /// <summary>打开并读取</summary>
        /// <param name="file">文件信息</param>
        /// <param name="compressed">是否压缩</param>
        /// <param name="func">要对文件流操作的委托</param>
        /// <returns></returns>
        public static T OpenRead<T>(this FileInfo file, Boolean compressed, Func<Stream, T> func)
        {
            if (compressed)
            {
                using var fs = file.OpenRead();
                using var gs = new GZipStream(fs, CompressionMode.Decompress, true);
                using var bs = new BufferedStream(gs);
                return func(bs);
            }
            else
            {
                using var fs = file.OpenRead();
                return func(fs);
            }
        }

        public static byte[] ReadFile(string fileName)
        {
            using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate))
            {
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Seek(0, SeekOrigin.Begin);
                return buffer;
            }
        }

    }
}
